﻿using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Logging;

using PLCS.Application.Contracts.TaskApp.Dtos;
using PLCS.Domain.Tasks;

using Prism.Commands;

using Volo.Abp.ObjectMapping;

namespace PLCS.App.OrderTask.ViewModels.TaskModule;

internal class TaskViewModel : NavigationPagedCurdViewModel<TaskDto, TaskEditDto, ITaskService>
{
    private readonly IObjectMapper<OrderTaskModule> _objectMapper;
    private readonly ILogger<TaskViewModel> _logger;
    private string _taskId, _taskType, _taskStatus, _trayNo;

    public string TaskId
    {
        get { return _taskId; }
        set { SetProperty(ref _taskId, value); }
    }

    public string TaskType
    {
        get { return _taskType; }
        set { SetProperty(ref _taskType, value); }
    }

    public string TaskStatus
    {
        get { return _taskStatus; }
        set { SetProperty(ref _taskStatus, value); }
    }

    public string TrayNo
    {
        get { return _trayNo; }
        set { SetProperty(ref _trayNo, value); }
    }

    public TaskViewModel(IObjectMapper<OrderTaskModule> objectMapper, ITaskService service, ILogger<TaskViewModel> logger) : base(service)
    {
        _objectMapper = objectMapper;
        _logger = logger;
        SubmitCommand = new DelegateCommand<TaskDto>(Submit);
        AgainIssuedCommand = new DelegateCommand<TaskDto>(AgainIssued);
        View = "任务管理";
    }

    private async void Submit(TaskDto model)
    {
        if (model.TaskStatus == Domain.Shared.Tasks.TaskStatus.解析失败)
        {
            ShowMessage("解析失败的任务无法手动报工，请点击删除。");
        }
        try
        {
            await _service.FinshTaskAsync(model.Id);
            DataGridList.Remove(model);
            Log("手动报工", model);
            ShowMessage("手动报工成功");
        }
        catch (Exception ex)
        {
            ShowMessage("手动报工失败");
            _logger.LogException(ex);
        }
    }

    private async void AgainIssued(TaskDto model)
    {
        try
        {
            await _service.AgainIssuedAsync(model.Id);
            Log("重新下发", model);
            await RefreshAsync();
            ShowMessage("重新下发成功");
        }
        catch (Exception ex)
        {
            ShowMessage("重新下发失败");
            _logger.LogException(ex);
        }
    }

    public DelegateCommand<TaskDto> SubmitCommand { get; }

    public DelegateCommand<TaskDto> AgainIssuedCommand { get; }

    /// <summary>
    /// 获取数据
    /// </summary>
    /// <param name="pageIndex"></param>
    public override async Task GetPageData(int pageIndex)
    {
        try
        {
            UpdateLoading(true);
            var res = await _service.GetListBySearchAsync((pageIndex - 1) * PageSize, PageSize, TaskId, TaskType, TaskStatus, TrayNo);
            TotalCount = (int)res.TotalCount;
            SetPageCount();
            DataGridList = res.Items.ToObservable();
        }
        finally
        {
            UpdateLoading(false);
        }
    }
}